
import request from './request'
import { parseTime } from './index'
const tokenKey = 'Authorization'

export function getToken() {
  return localStorage.getItem(tokenKey)
}

export function setToken(token) {
  return localStorage.setItem(tokenKey, token)
}

export function removeToken() {
  return localStorage.setItem(tokenKey, '')
}

export function getEnum() {
  return JSON.parse(localStorage.getItem("EnumsKey"))
}

export function setEnums(enums) {
  return localStorage.setItem("EnumsKey", JSON.stringify(enums))
}
export function setGlobal(data) {
  return localStorage.setItem("GLOBAL", JSON.stringify(data));
}
export function getGlobal() {
  return JSON.parse(localStorage.getItem("GLOBAL"))
}
export default {
  tokenKey,
  install: (Vue) => {
    Vue.prototype.$enums = getEnum()
    Vue.prototype.$global = getGlobal()
    Vue.prototype.$get = function (url) {
      return request({
        url: url,
        method: 'get'
      })
    }
    Vue.prototype.$post = function (url, data) {
      return request({
        url: url,
        method: 'post',
        data
      })
    }
    Vue.prototype.$form = function (url, data, method = 'post') {
      const formData = new FormData();
      for (var item in data) {
        if (data[item] === undefined || data[item] === null) continue;
        formData.append(item, data[item])
      }
      return request({
        url: url,
        method: method,
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        },
        data: formData
      })
    }
    Vue.prototype.$delete = function (url) {
      return request({
        url: url,
        method: "delete"
      })
    }
    Vue.prototype.$htmlFunction = {
      parseTime: function (date, fomat, icon = true) {
        var html = []
        if (icon) {
          html.push("<i class='el-icon-time'></i>")
        }
        if (fomat) {
          html.push('<span>' + date | parseTime('{y}-{m}-{d} {h}:{i}') + '</span>')
        } else {
          html.push('<span> ' + parseTime(date, '{y}-{m}-{d} {h}:{i}') + '</span>')
        }
        return html.join(' ')
      }
    }
  }
}
